package com.kgcx.schedule.service;

import com.kgcx.core.exception.BusinessException;
import com.kgcx.core.utils.HelpUtil;
import com.kgcx.core.utils.JsonUtil;
import com.kgcx.dbutils.core.mapper.BaseMapper;
import com.kgcx.dbutils.core.model.ParameterMap;
import com.kgcx.schedule.domain.ScheduleParameterDomain;
import com.kgcx.schedule.mapper.ScheduleParameterMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
// @Transactional(rollbackFor = Exception.class)
public class ScheduleParameterService extends BaseBusinessService<Long, ScheduleParameterDomain> {
    // private static final Logger LOG = LoggerFactory.getLogger(ScheduleParameterService.class);

    @Autowired
    private ScheduleParameterMapper scheduleParameterMapper;

    @Override
    protected BaseMapper<Long, ScheduleParameterDomain> getMapper() {
        return scheduleParameterMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertEntity(ScheduleParameterDomain entity) {
        if (selectParameter(entity.getCode(), entity.getCity_id()) != null) {
            throw new BusinessException(1L, "已经存在该参数配置，无法新增！");
        }

        entity.setCreate_id(0L);
        entity.setCreate_time(HelpUtil.getNowTime());

        super.insertEntity(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEntity(ScheduleParameterDomain entity) {
        entity.setUpdate_id(0L);
        entity.setUpdate_time(HelpUtil.getNowTime());

        super.updateEntity(entity);
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public ScheduleParameterDomain selectParameter(String code, Long city_id) {
        return scheduleParameterMapper
                .selectParameterByCodeAndCity(new ParameterMap("code", code).put("city_id", city_id));
    }

    public <T> T getParameterValue(Long city_id, Class<T> clazz) {
        ScheduleParameterDomain p = selectParameter(clazz.getName(), city_id);
        if (p == null) {
            return null;
        }

        return JsonUtil.toObject(p.getValue(), clazz);
    }
}
